<template>
  <div class="company-management">
    <el-row :gutter="20" class="mb-20">
      <el-col :span="8">
        <el-select v-model="selectedPort" placeholder="请选择港口" style="width: 100%" @change="handlePortChange">
          <el-option v-for="port in portList" :key="port.id" :label="port.name" :value="port.id" />
        </el-select>
      </el-col>
      <el-col :span="8">
        <el-switch v-model="onlyRemaining" active-text="仅显示有剩余仓储公司" @change="handlePortChange" />
      </el-col>
      <el-col :span="8">
        <el-button type="primary" @click="showAddDialog">添加公司</el-button>
      </el-col>
    </el-row>

    <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading">
      <el-table-column prop="id" label="id" width="80" />
      <el-table-column prop="name" label="公司名称" width="200" />
      <el-table-column prop="manager" label="经理" width="120" />
      <el-table-column prop="phone" label="联系电话" width="150" />
      <el-table-column prop="portId" label="所属港口" width="150" />
      <el-table-column prop="feeRate" label="定制费率" width="200" />
      <el-table-column prop="freeDays" label="定制免费天数" width="300" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="经理" prop="manager">
          <el-input v-model="form.manager" placeholder="请输入经理名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="所属港口" prop="portId">
          <el-select v-model="form.portId" placeholder="请选择港口" style="width: 100%">
            <el-option v-for="port in portList" :key="port.id" :label="port.name" :value="port.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="定制费率" prop="feeRate">
          <el-input-number 
            v-model="form.feeRate" 
            :min="0" 
            :precision="2" 
            :step="0.01"
            clearable
            placeholder="请输入定制费率（元/吨/天）" />
        </el-form-item>
        <el-form-item label="定制免费天数" prop="freeDays">
          <el-input-number 
            v-model="form.freeDays" 
            :min="0" 
            :max="365"
            clearable
            placeholder="请输入定制免费天数" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllPorts } from '@/api/port'
import { getAllCompanies, getCompaniesByPortId, getCompaniesWithRemainingWeightByPortId } from '@/api/company'
import { createCompany, updateCompany, deleteCompany } from '@/api/setting'

const tableData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加公司')
const formRef = ref(null)

const portList = ref([])
const selectedPort = ref(null)
const onlyRemaining = ref(false)

const form = ref({
  id: null,
  name: '',
  manager: '',
  phone: '',
  portId: null,
  feeRate: null,
  freeDays: null
})

const rules = {
  name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  manager: [{ required: true, message: '请输入经理', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  portId: [{ required: true, message: '请选择所属港口', trigger: 'change' }]
}

const fetchPorts = async () => {
  try {
    const res = await getAllPorts()
    portList.value = res.data
  } catch (e) {
    ElMessage.error('获取港口列表失败')
  }
}

const fetchData = async () => {
  loading.value = true
  try {
    if (selectedPort.value) {
      if (onlyRemaining.value) {
        const response = await getCompaniesWithRemainingWeightByPortId(selectedPort.value)
        tableData.value = response.data
      } else {
        const response = await getCompaniesByPortId(selectedPort.value)
        tableData.value = response.data
      }
    } else {
      const response = await getAllCompanies()
      tableData.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handlePortChange = () => {
  fetchData()
}

const showAddDialog = () => {
  dialogTitle.value = '添加公司'
  form.value = {
    id: null,
    name: '',
    manager: '',
    phone: '',
    portId: null,
    feeRate: null,
    freeDays: null
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑公司'
  form.value = { 
    ...row,
    portId: row.portId || row.port_id
  }
  dialogVisible.value = true
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该公司?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteCompany(id)
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const submitForm = async () => {
  try {
    await formRef.value.validate()

    // 只传有值的字段
    const submitData = { ...form.value }
    if (submitData.feeRate === null || submitData.feeRate === '' || typeof submitData.feeRate === 'undefined') {
      delete submitData.feeRate
    }
    if (submitData.freeDays === null || submitData.freeDays === '' || typeof submitData.freeDays === 'undefined') {
      delete submitData.freeDays
    }

    if (form.value.id) {
      await updateCompany(submitData)
      ElMessage.success('更新成功')
    } else {
      await createCompany(submitData)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

onMounted(() => {
  fetchPorts()
  fetchData()
})
</script>

<style scoped>
.mb-20 {
  margin-bottom: 20px;
}
</style> 